// Copyright 2002 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.

import java.io.*;
import java.util.*;
import javax.microedition.io.*;


/**
 * This class accepts and queues POST requests for a particular URL, and
 * services them in first-in-first-out order. Using the queue allows it
 * to be thread-safe without forcing its clients ever to block.
 */
public class HttpPoster
    implements Runnable
{
    private String url;
    private volatile boolean aborting = false;
    private Vector requestQueue = new Vector();
    private Vector listenerQueue = new Vector();
    private String parteOfUrl;
    private SalvaPreferencias record;


    public HttpPoster(String url)
    {
        this.url = url;
        Thread thread = new Thread(this);
        thread.start();
    }


    public synchronized void sendRequest(String request,String parteOfUrl,
                                         HttpPosterListener listener)
        throws IOException
    {
        requestQueue.addElement(request);
        listenerQueue.addElement(listener);
        this.parteOfUrl = parteOfUrl;
        notify();                    // wake up sending thread
    }


    public void run()
    {
    running:
        while (!aborting)
        {
            String request;
            HttpPosterListener listener;

            synchronized (this)
            {
                while (requestQueue.size() == 0)
                {
                    try
                    {
                        wait();     // releases lock
                    }
                    catch (InterruptedException e)
                    {
                    }

                    if (aborting)
                        break running;
                }

                request = (String)(requestQueue.elementAt(0));
                listener = (HttpPosterListener)(listenerQueue.elementAt(0));
                requestQueue.removeElementAt(0);
                listenerQueue.removeElementAt(0);
            }

            // sendRequest must have notified us
            doSend(request, listener);
        }
    }


    private void doSend(String request,  
                        HttpPosterListener listener)
    {
    	record = new SalvaPreferencias();
		record.openRecStore();
        HttpConnection conn = null;
        InputStream in = null;
        OutputStream out = null;
        String cookie = null;
        if(record.readRecord(3) != null)
        {
        		if(!record.readRecord(3).equals(""))
        		{
        			cookie = new String(record.readRecord(3));
        		}
        }
        else
        {
        	cookie = null;
        }
        byte[] responseBuf = null;
        String errorStr = null;
        boolean wasError = false;
        
        try
        {
            conn = (HttpConnection)Connector.open(url+parteOfUrl);

            // Set the request method and headers
            conn.setRequestMethod(HttpConnection.POST);

            conn.setRequestProperty("Content-Length",
                                    Integer.toString(request.length()));
            conn.setRequestProperty("Content-Type",
            		"application/x-www-form-urlencoded");
            
            //If you have a cook, send it
            if( cookie != null ){
                conn.setRequestProperty(
                 "Cookie", "JSESSIONID="+cookie );
            }
            
            // Getting the output stream may flush the headers
            out = conn.openOutputStream();
            
            int requestLength = request.length();
            for (int i = 0; i < requestLength; ++i)
            {
                out.write(request.charAt(i));
            }

            // Connect, then read cookie value
            // if we don't have one already
            
            int rc = conn.getResponseCode();

            if( cookie == null ){
                cookie = readCookie(conn).substring(11);
                //System.out.println("Co: "+cookie);
            }
            
            // Opening the InputStream will open the connection
            // and read the HTTP headers. They are stored until
            // requested.
            in = conn.openInputStream();
            System.out.println("Entrei");
            // Get the length and process the data
            long length = conn.getLength();
            if (length > 0)
            {
            	
            	responseBuf = new byte[(int)length];
            }
            else
            {
            	//System.out.println("Entrei aqui");
                //responseBuf = new byte[100];  // default length
            }
           
            int ch = in.read();
            int indice = 0;
            
            while ((ch != -1))
            {
            	responseBuf[indice] = (byte)ch;
                ch = in.read();
                indice++;
            }
            
            
        }
        catch (IOException e)
        {
            wasError = true;
            errorStr = e.getMessage();
            
        }
        catch (SecurityException e)
        {
            wasError = true;
            errorStr = e.getMessage();
        }
        catch(NullPointerException e)
        {
        	wasError = true;
            errorStr = e.getMessage();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                }
            }
            if (conn != null)
            {
                try
                {
                    conn.close();
                }
                catch (IOException e)
                {
                }
            }
            //System.out.println("Passou4");
            record.writeRecord(3, cookie);
           // record.closeRecStore();
            //record.openRecStore();
            if(record.readRecord(3) != null)
			{
				cookie = new String(record.readRecord(3));
				//System.out.println("Cookie: "+cookie);
			}
            record.closeRecStore();
        }

        if (wasError)
        {
            listener.handleHttpError(errorStr);
        }
        else
        {
            listener.receiveHttpResponse(responseBuf);
        }
        //System.out.println("Passou3");
    }


    private String readCookie(HttpConnection conn) throws IOException {
		
    	 String   key;
         String   value;
         String[] substrs;

         for( int i = 0;
              ( key = conn.getHeaderFieldKey( i ) )
                                          != null;
              ++i ){

             key = key.toLowerCase();

             if( key.equals( "set-cookie" ) ){
                 value = conn.getHeaderField( i );

                 while( value != null ){
                     substrs = split( value, ';' );
                     if( substrs[0].startsWith(
                                 "JSESSIONID=" ) ){
                         return substrs[0];
                     }

                     value = substrs[1];
                 }
             }
         }

         return null;
    }


	// Utility routine to split a string into two.

    public static String[] split( String in, char ch ){
        String[] result = new String[2];
        int      pos = in.indexOf( ch );

        if( pos != -1 ){
            result[0] = in.substring( 0, pos ).trim();
            result[1] = in.substring( pos+1 ).trim();
        } else {
            result[0] = in.trim();
        }

        return result;
    }



	// This is just for tidying up - the instance is useless after it has
    // been called
    public void abort()
    {
        aborting = true;
        synchronized (this)
        {
            notify();    // wake up our posting thread and kill it
        }
    }
}


